package com.baike.controller;
import com.alibaba.fastjson.JSONObject;
import com.baike.data.Result;
import com.baike.em.ConstantEnum;
import com.baike.entity.TbLesson;
import com.baike.entity.TbStudent;
import com.baike.entity.User;
import com.baike.mapper.TbLessonMapper;
import com.baike.service.ITbLessonService;
import com.baike.util.CookieUtils;
import com.baike.util.ShiroUtils;
import io.netty.util.Constant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RequestMapping("cartController")
@RestController
@RefreshScope
@Api("购物车功能接口")
public class CartController {

    @Autowired
    private ITbLessonService lessonService;
    @Autowired
    private TbLessonMapper tbLessonMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "获取购物车数据")
    @GetMapping("getCart")
    public Result getCart(HttpServletRequest request, HttpServletResponse response, String uuid){
        //获取登陆用户
        String userName = (String) redisTemplate.boundValueOps(uuid).get();

        //从cookie中获取数据
        String cookieValue = CookieUtils.getCookieValue(request, "cartList", true);
        if (StringUtils.isBlank(cookieValue)){
            cookieValue="[]";
        }
        List<TbLesson> lessonListCookie = JSONObject.parseArray(cookieValue, TbLesson.class);

        if (userName == null){
            //如果用户未登录,从cookie中获取
            return Result.build(ConstantEnum.SUCCESS).setResult(lessonListCookie);
        } else {
            //如果用户已登录
            List<TbLesson> listCartFromRedis = (List<TbLesson>) redisTemplate.boundHashOps("cartList").get(userName);
            //判断cookie中是否有数据,有就合并,没有就直接返回redis中的数据
            if (lessonListCookie.size() > 0){ //如果listCartFromRedis 大于 0  说明有数据
                //合并购物车
                List<TbLesson> cartList = lessonService.merageCartList(lessonListCookie,listCartFromRedis,userName);
                //将合并过后的数据放到redis
                lessonService.addCartListToRedis(cartList,userName);
                //清空cookie数据
                CookieUtils.deleteCookie(request,response,"cartList");
                return  Result.build(ConstantEnum.SUCCESS).setResult(cartList);
            }else {
                return Result.build(ConstantEnum.SUCCESS).setResult(listCartFromRedis);
            }
        }
    }

    //添加购物车
    @ApiOperation(value = "添加购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lessonId",value = "课程ID",required = true,paramType = "query"),
            @ApiImplicitParam(name = "uuid",value = "用户登录生成的UUID",required = true,paramType = "query")
    })
    @PostMapping("addCart")
    public  Result addCart(HttpServletRequest request, HttpServletResponse response, @RequestParam("lessonId") Long lessonId,@RequestParam("uuid") String uuid){
        //根据lesson_id查询lesson对象,要加入购物车的课程
        TbLesson lesson = tbLessonMapper.selectById(lessonId);
        //判断用户是否登陆
        String userName = (String) redisTemplate.boundValueOps(uuid).get();
        //获取cookie中的信息
        String cookieValue = CookieUtils.getCookieValue(request, "TblessonList", true);
        if (StringUtils.isBlank(cookieValue)){
            cookieValue = "[]";
        }
        List<TbLesson> cookieList = JSONObject.parseArray(cookieValue, TbLesson.class);
        //判断cookieList集合是否已经存在lesson对象
        for (TbLesson tbLesson : cookieList) {
            //如果相等说明 cookie里已经有这个对象,已加入了
            if (tbLesson.equals(lesson)){
                return Result.build(ConstantEnum.ALREADY_ADDED_TO_SHOPPING_CART);
            }else {
                //说明cookie 没有,往cookie里添加
                CookieUtils.setCookie(request,response,"TblessonList",cookieValue,true);
            }
        }
        //如果等于null 说明没登录
        if (Objects.isNull(userName)){
            return Result.build(ConstantEnum.NO_LOGIN).setResult(cookieList);
        }else {
            //已登录,查询redis该用户有没有购物车
            Boolean hasKey = redisTemplate.boundHashOps("cartList").hasKey(userName);

            if(!hasKey){
                //没有就新建一个
                List<TbLesson> lessonList = new ArrayList<>();
                lessonList.add(lesson);
                //将课程存入redis
                redisTemplate.boundHashOps("cartList").put(userName,lessonList);
            }
            //判断是否重复
            List<TbLesson> lessonList = (List<TbLesson>) redisTemplate.boundHashOps("cartList").get(userName);
            for (TbLesson tbLesson : lessonList) {
                if(tbLesson.equals(lesson)){
                    return Result.build(ConstantEnum.SUCCESS);
                }
            }
            lessonList.add(lesson);
            //存入redis
            redisTemplate.boundHashOps("cartList").put(userName,lessonList);
        }
        return Result.build(ConstantEnum.SUCCESS);
    }

    @ApiOperation(value = "查看我的购物车")
    @GetMapping("selectShoppingCart")
    public Result selectShoppingCart(String uuid){
        //判断用户是否登陆
        String userName = (String) redisTemplate.boundValueOps(uuid).get();
         //如果等于null 说明没登录
        if (Objects.isNull(userName)){
            return Result.build(ConstantEnum.NO_LOGIN);//未登录
        }else {
            //已登录,从redis中获取购物车
            List<TbLesson> lessonList = (List<TbLesson>) redisTemplate.boundHashOps("cartList").get(userName);
            return Result.build(ConstantEnum.SUCCESS).setResult(lessonList);
        }

    }


}
